package com.fuxi.cloud.dyndb;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.fuxi.cloud.common.expetion.JimuReportException;
import com.fuxi.cloud.common.util.ReflectHelper;
import com.fuxi.cloud.common.util.oConvertUtils;
import com.fuxi.cloud.config.HikariDataSourceConfig;
import com.fuxi.cloud.dyndb.util.JmreportFreemarkerParseFactory;
import com.fuxi.cloud.dyndb.vo.JmreportDynamicDataSourceVo;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JmreportDynamicDbUtil
 *
 * @Author: 扫地僧
 * @CreateTime: 2021-05-03
 */

@Component("JmreportDynamicDbUtil")
public class JmreportDynamicDbUtil {
    private static final Logger log = LoggerFactory.getLogger(JmreportDynamicDbUtil.class);
    @Resource
    private HikariDataSourceConfig hikariDataSourceConfig;

    public JmreportDynamicDbUtil() {
    }

    /** @deprecated */
    @Deprecated
    private DruidDataSource getDruidDataSource(JmreportDynamicDataSourceVo dbSource) {
        DruidDataSource var2 = new DruidDataSource();
        String var3 = dbSource.getDbDriver();
        String var4 = dbSource.getDbUrl();
        String var5 = dbSource.getDbUsername();
        String var6 = dbSource.getDbPassword();
        var2.setDriverClassName(var3);
        var2.setUrl(var4);
        var2.setTestWhileIdle(true);
        var2.setTestOnBorrow(false);
        var2.setTestOnReturn(false);
        var2.setBreakAfterAcquireFailure(true);
        var2.setConnectionErrorRetryAttempts(0);
        var2.setUsername(var5);
        var2.setMaxWait(60000L);
        var2.setPassword(var6);
        log.debug("******************************************");
        log.debug("*                                        *");
        log.debug("*====【" + dbSource.getCode() + "】=====Druid连接池已启用 ====*");
        log.debug("*                                        *");
        log.debug("******************************************");
        return var2;
    }

    private HikariDataSource getHikariDataSource(JmreportDynamicDataSourceVo dbSource) {
        HikariDataSource var2 = new HikariDataSource();
        String var3 = dbSource.getDbDriver();
        String var4 = dbSource.getDbUrl();
        String var5 = dbSource.getDbUsername();
        String var6 = dbSource.getDbPassword();
        var2.setDriverClassName(var3);
        var2.setJdbcUrl(var4);
        var2.setUsername(var5);
        var2.setPassword(var6);
        var2.setAutoCommit(this.hikariDataSourceConfig.getAutoCommit());
        var2.setMaximumPoolSize(this.hikariDataSourceConfig.getMaximumPoolSize());
        var2.setMinimumIdle(this.hikariDataSourceConfig.getMinimumDdle());
        var2.setConnectionTimeout((long)this.hikariDataSourceConfig.getConnectionTimeout());
        var2.setIdleTimeout((long)this.hikariDataSourceConfig.getIdleTimeout());
        var2.setMaxLifetime((long)this.hikariDataSourceConfig.getMaxLifetime());
        var2.setPoolName(this.hikariDataSourceConfig.getPoolName());
        log.debug("******************************************");
        log.debug("*                                        *");
        log.debug("*====【" + dbSource.getCode() + "】=====Hikari连接池已启用 ====*");
        log.debug("*                                        *");
        log.debug("******************************************");
        return var2;
    }

    public DataSource getDbSourceByDbKey(String dbKey) {
        log.debug("----自定义动态数据源----------dbKey------: " + dbKey);
        DataSource var2 = JmreportDataSourceCachePool.getCacheBasicDataSource(dbKey);

        try {
            if (var2 != null) {
                log.debug("--------getDbSourceBydbKey------------------从缓存中获取DB连接-------------------");
                return var2;
            } else {
                JmreportDynamicDataSourceVo var3 = JmreportDataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
                if (var3 == null) {
                    throw new JimuReportException("动态数据源连接不存在，dbKey：" + dbKey);
                } else {
                    HikariDataSource var4 = this.getHikariDataSource(var3);
                    if (var4 != null) {
                        JmreportDataSourceCachePool.putCacheBasicDataSource(dbKey, var4);
                        log.debug("--------getDbSourceBydbKey------------------创建DB数据库连接-------------------");
                        return var4;
                    } else {
                        throw new JimuReportException("动态数据源连接失败，dbKey：" + dbKey);
                    }
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
            return var2;
        }
    }

    public void closeDbKey(String dbKey) {
        DataSource var2 = this.getDbSourceByDbKey(dbKey);

        try {
            if (var2 != null && !var2.getConnection().isClosed()) {
                var2.getConnection().commit();
                var2.getConnection().close();
                var2.getConnection().close();
            }
        } catch (SQLException var4) {
            var4.printStackTrace();
        }

    }

    private JdbcTemplate getJdbcTemplate(String dbKey) {
        DataSource var2 = this.getDbSourceByDbKey(dbKey);
        return new JdbcTemplate(var2);
    }

    public int update(String dbKey, String sql, Object... param) {
        JdbcTemplate var5 = this.getJdbcTemplate(dbKey);
        int var4;
        if (ObjectUtil.isEmpty(param)) {
            var4 = var5.update(sql);
        } else {
            var4 = var5.update(sql, param);
        }

        return var4;
    }

    public int updateByHash(String dbKey, String sql, HashMap<String, Object> data) {
        JdbcTemplate var5 = this.getJdbcTemplate(dbKey);
        sql = JmreportFreemarkerParseFactory.parseTemplateContent(sql, data);
        NamedParameterJdbcTemplate var6 = new NamedParameterJdbcTemplate(var5.getDataSource());
        int var4 = var6.update(sql, data);
        return var4;
    }

    public Object findOne(String dbKey, String sql, Object... param) {
        List var4 = this.findList(dbKey, sql, param);
        if (oConvertUtils.listIsEmpty(var4)) {
            log.error("Except one, but not find actually");
        }

        if (var4.size() > 1) {
            log.error("Except one, but more than one actually");
        }

        return var4.get(0);
    }

    public Object findOneByHash(String dbKey, String sql, HashMap<String, Object> data) {
        List var4 = this.findListByHash(dbKey, sql, data);
        if (oConvertUtils.listIsEmpty(var4)) {
            log.error("Except one, but not find actually");
        }

        if (var4.size() > 1) {
            log.error("Except one, but more than one actually");
        }

        return var4.get(0);
    }

    public <T> Object findOne(String dbKey, String sql, Class<T> clazz, Object... param) {
        Map var5 = (Map)this.findOne(dbKey, sql, param);
        return ReflectHelper.setAll(clazz, var5);
    }

    public <T> Object findOneByHash(String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
        Map var5 = (Map)this.findOneByHash(dbKey, sql, data);
        return ReflectHelper.setAll(clazz, var5);
    }

    public List<Map<String, Object>> findList(String dbKey, String sql, Object... param) {
        JdbcTemplate var5 = this.getJdbcTemplate(dbKey);
        List var4;
        if (ObjectUtil.isEmpty(param)) {
            var4 = var5.queryForList(sql);
        } else {
            var4 = var5.queryForList(sql, param);
        }

        return var4;
    }

    public List<Map<String, Object>> findListByHash(String dbKey, String sql, HashMap<String, Object> data) {
        JdbcTemplate var5 = this.getJdbcTemplate(dbKey);
        sql = JmreportFreemarkerParseFactory.parseTemplateContent(sql, data);
        NamedParameterJdbcTemplate var6 = new NamedParameterJdbcTemplate(var5.getDataSource());
        List var4 = var6.queryForList(sql, data);
        return var4;
    }

    public <T> List<T> findList(String dbKey, String sql, Class<T> clazz, Object... param) {
        JdbcTemplate var6 = this.getJdbcTemplate(dbKey);
        List var5;
        if (ObjectUtil.isEmpty(param)) {
            var5 = var6.queryForList(sql, clazz);
        } else {
            var5 = var6.queryForList(sql, clazz, param);
        }

        return var5;
    }

    public <T> List<T> findListByHash(String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
        JdbcTemplate var6 = this.getJdbcTemplate(dbKey);
        sql = JmreportFreemarkerParseFactory.parseTemplateContent(sql, data);
        NamedParameterJdbcTemplate var7 = new NamedParameterJdbcTemplate(var6.getDataSource());
        List var5 = var7.queryForList(sql, data, clazz);
        return var5;
    }

    public <T> List<T> findListEntities(String dbKey, String sql, Class<T> clazz, Object... param) {
        List var5 = this.findList(dbKey, sql, param);
        return ReflectHelper.transList2Entrys(var5, clazz);
    }

    public <T> List<T> findListEntitiesByHash(String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
        List var5 = this.findListByHash(dbKey, sql, data);
        return ReflectHelper.transList2Entrys(var5, clazz);
    }
}

